"""
列顺序调整对话框
提供拖拽和手动调整列顺序的功能
"""

from typing import List, Optional
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                              QPushButton, QListWidget, QListWidgetItem, 
                              QDialogButtonBox, QGroupBox, QSpinBox, QFormLayout)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QDragEnterEvent, QDropEvent, QDragMoveEvent


class ColumnReorderDialog(QDialog):
    """列顺序调整对话框"""
    
    column_order_changed = Signal(list)  # 列顺序改变信号
    
    def __init__(self, parent=None, headers: List[str] = None, current_order: List[int] = None):
        super().__init__(parent)
        self.setWindowTitle("调整列顺序")
        self.setModal(True)
        self.resize(500, 400)
        
        self.headers = headers or []
        self.current_order = current_order or list(range(len(self.headers)))
        
        self.setup_ui()
        self.load_columns()
        
    def setup_ui(self):
        """设置界面"""
        layout = QVBoxLayout(self)
        
        # 说明文字
        info_label = QLabel("拖拽列表项来调整列顺序，或使用按钮进行移动")
        info_label.setWordWrap(True)
        layout.addWidget(info_label)
        
        # 列列表
        self.column_list = QListWidget()
        self.column_list.setDragDropMode(QListWidget.InternalMove)
        self.column_list.setAcceptDrops(True)
        self.column_list.setDragEnabled(True)
        self.column_list.setDropIndicatorShown(True)
        layout.addWidget(self.column_list)
        
        # 按钮组
        button_layout = QHBoxLayout()
        
        # 移动按钮
        move_group = QGroupBox("移动列")
        move_layout = QFormLayout(move_group)
        
        self.from_spinbox = QSpinBox()
        self.from_spinbox.setMinimum(0)
        self.from_spinbox.setMaximum(len(self.headers) - 1)
        move_layout.addRow("从位置:", self.from_spinbox)
        
        self.to_spinbox = QSpinBox()
        self.to_spinbox.setMinimum(0)
        self.to_spinbox.setMaximum(len(self.headers) - 1)
        move_layout.addRow("到位置:", self.to_spinbox)
        
        move_btn = QPushButton("移动")
        move_btn.clicked.connect(self.move_column)
        move_layout.addRow("", move_btn)
        
        button_layout.addWidget(move_group)
        
        # 重置按钮
        reset_btn = QPushButton("重置顺序")
        reset_btn.clicked.connect(self.reset_order)
        button_layout.addWidget(reset_btn)
        
        layout.addLayout(button_layout)
        
        # 对话框按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        
    def load_columns(self):
        """加载列到列表"""
        self.column_list.clear()
        
        for i, col_index in enumerate(self.current_order):
            if 0 <= col_index < len(self.headers):
                header = self.headers[col_index]
                item = QListWidgetItem(f"{i+1}. {header}")
                item.setData(Qt.UserRole, col_index)
                self.column_list.addItem(item)
                
    def move_column(self):
        """移动列"""
        from_index = self.from_spinbox.value()
        to_index = self.to_spinbox.value()
        
        if from_index == to_index:
            return
            
        if 0 <= from_index < len(self.current_order) and 0 <= to_index < len(self.current_order):
            # 移动列
            item = self.current_order.pop(from_index)
            self.current_order.insert(to_index, item)
            
            # 更新列表显示
            self.load_columns()
            
            # 更新spinbox的最大值
            max_val = len(self.current_order) - 1
            self.from_spinbox.setMaximum(max_val)
            self.to_spinbox.setMaximum(max_val)
            
    def reset_order(self):
        """重置列顺序"""
        self.current_order = list(range(len(self.headers)))
        self.load_columns()
        
        # 更新spinbox的最大值
        max_val = len(self.current_order) - 1
        self.from_spinbox.setMaximum(max_val)
        self.to_spinbox.setMaximum(max_val)
        
    def get_column_order(self) -> List[int]:
        """获取当前列顺序"""
        return self.current_order.copy()
        
    def accept(self):
        """确认对话框"""
        # 发送列顺序改变信号
        self.column_order_changed.emit(self.current_order)
        super().accept()


class DragDropListWidget(QListWidget):
    """支持拖拽的列表控件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setDragDropMode(QListWidget.InternalMove)
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDropIndicatorShown(True)
        
    def dragEnterEvent(self, event: QDragEnterEvent):
        """拖拽进入事件"""
        if event.mimeData().hasFormat("application/x-qabstractitemmodeldatalist"):
            event.acceptProposedAction()
            
    def dragMoveEvent(self, event: QDragMoveEvent):
        """拖拽移动事件"""
        if event.mimeData().hasFormat("application/x-qabstractitemmodeldatalist"):
            event.acceptProposedAction()
            
    def dropEvent(self, event: QDropEvent):
        """拖拽放下事件"""
        if event.mimeData().hasFormat("application/x-qabstractitemmodeldatalist"):
            event.acceptProposedAction()
            super().dropEvent(event)


class ColumnReorderWidget(QDialog):
    """列顺序调整控件（简化版）"""
    
    def __init__(self, parent=None, headers: List[str] = None):
        super().__init__(parent)
        self.setWindowTitle("调整列顺序")
        self.setModal(True)
        self.resize(400, 300)
        
        self.headers = headers or []
        self.column_order = list(range(len(self.headers)))
        
        self.setup_ui()
        self.load_columns()
        
    def setup_ui(self):
        """设置界面"""
        layout = QVBoxLayout(self)
        
        # 说明
        info_label = QLabel("拖拽调整列顺序")
        layout.addWidget(info_label)
        
        # 列列表
        self.column_list = DragDropListWidget()
        layout.addWidget(self.column_list)
        
        # 按钮
        button_layout = QHBoxLayout()
        
        reset_btn = QPushButton("重置")
        reset_btn.clicked.connect(self.reset_order)
        button_layout.addWidget(reset_btn)
        
        button_layout.addStretch()
        
        ok_btn = QPushButton("确定")
        ok_btn.clicked.connect(self.accept)
        button_layout.addWidget(ok_btn)
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
        
    def load_columns(self):
        """加载列到列表"""
        self.column_list.clear()
        
        for i, col_index in enumerate(self.column_order):
            if 0 <= col_index < len(self.headers):
                header = self.headers[col_index]
                item = QListWidgetItem(f"{i+1}. {header}")
                item.setData(Qt.UserRole, col_index)
                self.column_list.addItem(item)
                
    def reset_order(self):
        """重置列顺序"""
        self.column_order = list(range(len(self.headers)))
        self.load_columns()
        
    def get_column_order(self) -> List[int]:
        """获取当前列顺序"""
        # 从列表项中提取列顺序
        order = []
        for i in range(self.column_list.count()):
            item = self.column_list.item(i)
            if item:
                col_index = item.data(Qt.UserRole)
                order.append(col_index)
        return order